package co.fitstart.weapp.api.web.controller.coach;

import java.util.List;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.MediaType;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

import com.demo2do.core.entity.result.HttpResult;
import com.demo2do.core.persistence.GenericDaoSupport;

import co.fitstart.entity.course.round.CourseRound;
import co.fitstart.entity.course.schedule.CourseSchedule;
import co.fitstart.entity.courseware.exercise.ExerciseContent;
import co.fitstart.entity.courseware.fitnessgroup.Courseware;
import co.fitstart.entity.courseware.fitnessgroup.FitnessGroup;
import co.fitstart.entity.principal.Principal;
import co.fitstart.weapp.api.entity.CoursewareRequest;
import co.fitstart.weapp.api.service.CoachService;
import co.fitstart.weapp.api.service.CourseRoundService;
import co.fitstart.weapp.api.service.CourseScheduleService;
import co.fitstart.weapp.api.service.CoursewareService;

/**
 * 
 * @author haiyan_xiao
 *
 */
@RestController
@RequestMapping("/coach/course-rounds/{courseRoundId}/schedule-coursewares")
public class ScheduleCoursewareController {

    private static final Logger logger = LoggerFactory.getLogger(ScheduleCoursewareController.class);

    @Autowired
    private CoachService coachService;

    @Autowired
    private CourseRoundService courseRoundService;

    @Autowired
    private CourseScheduleService courseScheduleService;

    @Autowired
    private CoursewareService coursewareService;

    @Autowired
    private GenericDaoSupport genericDaoSupport;

    /**
     * 
     * @param mobile
     * @param courseRoundId
     * @return
     */
    @RequestMapping(value = "", method = RequestMethod.GET, produces = MediaType.APPLICATION_JSON_UTF8_VALUE, params = "mobile")
    public HttpResult list(@RequestParam("mobile") String mobile,
                           @PathVariable("courseRoundId") Long courseRoundId) {
        HttpResult httpResult = new HttpResult();
        
        try {
            CourseRound courseRound = courseRoundService.load(courseRoundId);
            List<CourseSchedule> courseSchedules = coursewareService.generallyListScheduleCourseware(courseRound);
            
            httpResult.success().message("获取数据成功")
                                .data("courseSchedules", courseSchedules);
            
        } catch (Exception e) {
            logger.error("#ScheduleCoursewareController# list() error", e);
            httpResult.fail("500").message("加载数据失败");
        }
        
        return httpResult;
    }

    /**
     * 
     * @param mobile
     * @param courseRoundId
     * @param courseScheduleId
     * @return
     */
    @RequestMapping(value = "/{courseScheduleId}", method = RequestMethod.GET, produces = MediaType.APPLICATION_JSON_UTF8_VALUE, params = "mobile")
    public HttpResult view(@RequestParam("mobile") String mobile,
                           @PathVariable("courseRoundId") Long courseRoundId,
                           @PathVariable("courseScheduleId") Long courseScheduleId) {
        HttpResult httpResult = new HttpResult();
        
        try {
            Principal coach = coachService.load(mobile);
            CourseSchedule courseSchedule = courseScheduleService.load(courseScheduleId);
            List<Courseware> coursewares = coursewareService.listCourseware(courseSchedule);
            
            if(courseSchedule.getContent() == null) {
                coursewareService.initlizeContent(courseSchedule);
            }
            
            httpResult.success().message("获取数据成功")
                                .data("schedule", courseSchedule)
                                .data("courseName", courseSchedule.getCourse().getName())
                                .data("coachAvatar", courseSchedule.getCoach().getProfile() == null ? null : courseSchedule.getCoach().getProfile().getAvatar())
                                .data("needInbody", courseScheduleService.isFirstReady(courseSchedule) && courseRoundService.isInbodyNeeded(courseSchedule.getCourseRound()))
                                .data("isMainCoach", coach == courseSchedule.getCourseRound().getCoach())
                                .data("isScheduleCoach", coach == courseSchedule.getCoach())
                                .data("coursewares", coursewares);
        } catch (Exception e) {
            logger.error("#ScheduleCoursewareController# view() error", e);
            httpResult.fail("500").message("加载数据失败");
        }
        
        return httpResult;
    }

    /**
     * 
     * @param mobile
     * @param courseRoundId
     * @param courseScheduleId
     * @return
     */
    @RequestMapping(value = "/{courseScheduleId}/content", method = RequestMethod.GET, produces = MediaType.APPLICATION_JSON_UTF8_VALUE, params = "mobile")
    public HttpResult content(@RequestParam("mobile") String mobile,
                              @PathVariable("courseRoundId") Long courseRoundId,
                              @PathVariable("courseScheduleId") Long courseScheduleId) {
        HttpResult httpResult = new HttpResult();
        
        try {
            CourseSchedule courseSchedule = courseScheduleService.load(courseScheduleId);
            
            httpResult.success().message("获取数据成功")
                                .data("content", coursewareService.getContent(courseSchedule));
        } catch (Exception e) {
            logger.error("#ScheduleCoursewareController# content() error", e);
            httpResult.fail("500").message("加载数据失败");
        }
        
        return httpResult;
    }

    /**
     * 
     * @param mobile
     * @param courseRoundId
     * @param courseScheduleId
     * @param contents
     * @return
     */
    @RequestMapping(value = "/{courseScheduleId}/edit-content", method = RequestMethod.POST, produces = MediaType.APPLICATION_JSON_UTF8_VALUE, params = "mobile")
    public HttpResult editContent(@RequestParam("mobile") String mobile,
                                  @PathVariable("courseRoundId") Long courseRoundId,
                                  @PathVariable("courseScheduleId") Long courseScheduleId,
                                  @RequestBody List<ExerciseContent> contents) {
        HttpResult httpResult = new HttpResult();
        
        try {
            Principal coach = coachService.load(mobile);
            CourseSchedule courseSchedule = courseScheduleService.load(courseScheduleId);
            
            if(coach == courseSchedule.getCourseRound().getCoach()) {
                coursewareService.editContent(courseSchedule, contents);
                
                httpResult.success().message("修改上课内容成功");
            } else {
                httpResult.fail("500").message("你不是主教练，不能修改上课内容");
            }
        } catch (Exception e) {
            logger.error("#ScheduleCoursewareController# editContent() error", e);
            httpResult.fail("500").message("修改上课内容失败");
        }
        
        return httpResult;
    }

    /**
     * 
     * @param mobile
     * @param courseRoundId
     * @param courseScheduleId
     * @param movementIds
     * @return
     */
    @RequestMapping(value = "/{courseScheduleId}/add-courseware", method = RequestMethod.POST, produces = MediaType.APPLICATION_JSON_UTF8_VALUE, params = "mobile")
    public HttpResult addCourseware(@RequestParam("mobile") String mobile,
                                  @PathVariable("courseRoundId") Long courseRoundId,
                                  @PathVariable("courseScheduleId") Long courseScheduleId,
                                  @RequestBody List<Long> movementIds) {
        HttpResult httpResult = new HttpResult();
        
        try {
            Principal coach = coachService.load(mobile);
            CourseSchedule courseSchedule = courseScheduleService.load(courseScheduleId);
            
            if(coach == courseSchedule.getCourseRound().getCoach()) {
                coursewareService.addCourseware(courseSchedule, movementIds);
                
                httpResult.success().message("添加动作成功");
            } else {
                httpResult.fail("500").message("你不是上课教练，不能添加动作");
            }
        } catch (Exception e) {
            logger.error("#ScheduleCoursewareController# addCourseware() error", e);
            httpResult.fail("500").message("添加动作失败");
        }
        
        return httpResult;
    }

    /**
     * 
     * @param mobile
     * @param courseRoundId
     * @param courseScheduleId
     * @param fitnessGroupId
     * @return
     */
    @RequestMapping(value = "/{courseScheduleId}/add-courseware-group", method = RequestMethod.POST, produces = MediaType.APPLICATION_JSON_UTF8_VALUE, params = "mobile")
    public HttpResult addCoursewareGroup(@RequestParam("mobile") String mobile,
                                       @PathVariable("courseRoundId") Long courseRoundId,
                                       @PathVariable("courseScheduleId") Long courseScheduleId,
                                       @RequestBody Long fitnessGroupId) {
        HttpResult httpResult = new HttpResult();
        
        try {
            Principal coach = coachService.load(mobile);
            CourseSchedule courseSchedule = courseScheduleService.load(courseScheduleId);
            
            if(coach == courseSchedule.getCourseRound().getCoach()) {
                FitnessGroup fitnessGroup = genericDaoSupport.load(FitnessGroup.class, fitnessGroupId);
                coursewareService.addCourseware(courseSchedule, fitnessGroup);
                
                httpResult.success().message("添加动作组成功");
            } else {
                httpResult.fail("500").message("你不是上课教练，不能添加动作组");
            }
        } catch (Exception e) {
            logger.error("#ScheduleCoursewareController# addCoursewareGroup() error", e);
            httpResult.fail("500").message("添加动作组失败");
        }
        
        return httpResult;
    }

    /**
     * 
     * @param mobile
     * @param courseRoundId
     * @param courseScheduleId
     * @param coursewareIds
     * @return
     */
    @RequestMapping(value = "/{courseScheduleId}/delete-courseware", method = RequestMethod.POST, produces = MediaType.APPLICATION_JSON_UTF8_VALUE, params = "mobile")
    public HttpResult deleteCourseware(@RequestParam("mobile") String mobile,
                                       @PathVariable("courseRoundId") Long courseRoundId,
                                       @PathVariable("courseScheduleId") Long courseScheduleId,
                                       @RequestBody List<Long> coursewareIds) {
        HttpResult httpResult = new HttpResult();
        
        try {
            Principal coach = coachService.load(mobile);
            CourseSchedule courseSchedule = courseScheduleService.load(courseScheduleId);
            
            if(coach == courseSchedule.getCourseRound().getCoach()) {
                coursewareService.deleteCourseware(courseSchedule, coursewareIds);
                
                httpResult.success().message("删除动作成功");
            } else {
                httpResult.fail("500").message("你不是上课教练，不能删除动作");
            }
        } catch (Exception e) {
            logger.error("#ScheduleCoursewareController# deleteCourseware() error", e);
            httpResult.fail("500").message("删除动作失败");
        }
        
        return httpResult;
    }

    /**
     * 
     * @param mobile
     * @param courseRoundId
     * @param courseScheduleId
     * @param coursewares
     * @return
     */
    @RequestMapping(value = "/{courseScheduleId}/edit-courseware", method = RequestMethod.POST, produces = MediaType.APPLICATION_JSON_UTF8_VALUE, params = "mobile")
    public HttpResult editCourseware(@RequestParam("mobile") String mobile,
                                       @PathVariable("courseRoundId") Long courseRoundId,
                                       @PathVariable("courseScheduleId") Long courseScheduleId,
                                       @RequestBody List<CoursewareRequest> coursewares) {
        HttpResult httpResult = new HttpResult();
        
        try {
            Principal coach = coachService.load(mobile);
            CourseSchedule courseSchedule = courseScheduleService.load(courseScheduleId);
            
            if(coach == courseSchedule.getCourseRound().getCoach()) {
                coursewareService.editCourseware(courseSchedule, coursewares);
                
                httpResult.success().message("修改动作成功");
            } else {
                httpResult.fail("500").message("你不是上课教练，不能修改动作");
            }
        } catch (Exception e) {
            logger.error("#ScheduleCoursewareController# coursewareIds() error", e);
            httpResult.fail("500").message("修改动作失败");
        }
        
        return httpResult;
    }

    /**
     * 
     * @param mobile
     * @param courseRoundId
     * @param courseScheduleId
     * @param coursewareId
     * @return
     */
    @RequestMapping(value = "/{courseScheduleId}/coursewares/{coursewareId}", method = RequestMethod.GET, produces = MediaType.APPLICATION_JSON_UTF8_VALUE, params = "mobile")
    public HttpResult viewCourseware(@RequestParam("mobile") String mobile,
                                     @PathVariable("courseRoundId") Long courseRoundId,
                                     @PathVariable("courseScheduleId") Long courseScheduleId,
                                     @PathVariable("coursewareId") Long coursewareId) {
        HttpResult httpResult = new HttpResult();
        
        try {
            Courseware courseware = genericDaoSupport.load(Courseware.class, coursewareId);
            
            if(!courseware.isDisabled()) {
                httpResult.success().message("获取数据成功")
                                    .data("courseware", courseware)
                                    .data("movement", courseware.getMovement())
                                    .data("equipment", courseware.getMovement().getEquipment());
            } else {
                httpResult.fail("500").message("获取数据失败");
            }
        } catch (Exception e) {
            logger.error("#ScheduleCoursewareController# viewCourseware() error", e);
            httpResult.fail("500").message("加载数据失败");
        }
        
        return httpResult;
    }
}
